import Vue from 'vue'
import Vuex from 'vuex'
import { getWxRetailerInfo } from "@/api/member"
import { getWxUserInfo } from "@/api/user"
import { getToken } from "@/utils/auth"

Vue.use(Vuex)


export default new Vuex.Store({
  state: {
    tabBarActive: +sessionStorage.getItem("tabBarActive") || 0,
    token: getToken(),
    retailer_id: -1,
    retailer_name: "",
    wx_staff: -1,
  },
  mutations: {
    SET_TABBAR_ACTIVE: (state, index) => {
      state.tabBarActive = index
      sessionStorage.setItem("tabBarActive", index)
    },
    SET_RETAILER_ID: (state, id) => {
      state.retailer_id = id
    },
    SET_RETAILER_NAME: (state, name) => {
      state.retailer_name = name
    },

    SET_WX_STAFF: (state, wx_staff) => {
      state.wx_staff = wx_staff
    },
  },
  actions: {
    setTabBarActive({ commit }, index) {
      console.log("index:", index);
      commit("SET_TABBAR_ACTIVE", index)
    },
    setRetailerId({ commit }, index) {
      commit("SET_RETAILER_ID", index)
    },

    setRetailerName({ commit }, name) {
      commit("SET_RETAILER_NAME", name)
    },
    
    setWxStaff({ commit }, wx_staff) {
      commit("SET_WX_STAFF", wx_staff)
    },

    getRetailerInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getWxRetailerInfo().then(res => {
          const data = res.data
          if (data.status_code == 200) {

            const { id, name, flag} = data.retailer;
            
            console.log(data.retailer);

            if( flag == 1){
              commit('SET_RETAILER_ID', id);
            } else{
              commit('SET_RETAILER_ID', -1);
            }
            
            commit('SET_RETAILER_NAME', name);
            
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    

    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getWxUserInfo().then(res => {
          if (!res) {
            return reject('读取用户信息数据失败.')
          }
          const { staff } = res.data

          commit('SET_WX_STAFF', staff)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

  },
  getters: {
    tabBarActive: state => state.tabBarActive,
    retailer_id: state => state.retailer_id,
    retailer_name: state => state.retailer_name,
    wx_staff: state => state.wx_staff,
  }
})